import time
import re
import json
import urllib
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import math
import base64
from urllib.parse import urlencode


class spider(BaseTaxPolicySpider):
    name = "dalian_dlslskqrmzf"

    province: str = "辽宁省"  # 取表格
    city: str = "大连市"  # 取表格
    county: str = "旅顺口区"  # 取表格
    park: str = "None"  # 取表格
    source: str = "大连市旅顺口区人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.dllsk.gov.cn/zfxxgk/index.html"  # 注明入口网址，以便后续排错

    def start_requests(self):
        url = "http://www.dllsk.gov.cn/zfxxgk/list79.asp?page=1&classid=5&itcn_B_ClassID=17&XClassID=79"

        yield scrapy.Request(
            url=url,
            method='GET',
            callback=self.detail_requests
        )

    def detail_requests(self, response, **kwargs):
        print(response.text)
        pattern = r"共&nbsp;\s*(\d+)\s*&nbsp;页"
        # 查找所有匹配项
        pages = int(re.findall(pattern, response.text)[0])
        print(f"总页数：{pages}")
        links = response.xpath('//li/a/@href').getall()
        for link in links:
            real_url = f"http://www.dllsk.gov.cn/zfxxgk/{link}"
            yield response.follow(real_url, callback=self.parse_detail)
        if response.meta.get("is_next") is not False:
            for page in range(2, pages + 1):
                print("当前页：", page)
                url = f"http://www.dllsk.gov.cn/zfxxgk/list79.asp?page={page}&classid=5&itcn_B_ClassID=17&XClassID=79"

                yield scrapy.Request(
                    url=url,
                    method='GET',
                    callback=self.detail_requests
                )

    def parse_list(self, response, **kwargs):
        pass

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['source_url'] = response.url
        pattern = r'<p class="tAlign-center">发表日期：(.*?)</p>'
        item['publish_date'] = re.findall(pattern, response.text)[0]
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        # print("item", item)
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl dalian_dlslskqrmzf".split())
